const { app, BrowserWindow, Menu, ipcMain } = require('electron')
const path = require('path')
const fs = require('fs')

global.shareObject = {
  calc: 'default',
  update: false
}

app.on('ready', () => {

  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 700,
    webPreferences: {
      nodeIntegration: true
    }
  })

  mainWindow.loadFile('./component/index/index.html')

  mainWindow.once('ready-to-show', () => {
    this.show()
  })

  console.log(mainWindow.id)

  ipcMain.on('open-files', (event) => {
    const filesWindow = new BrowserWindow({
      width: 370,
      height: 600,
      webPreferences: {
        nodeIntegration: true
      }
    })

    filesWindow.loadFile('./component/files/files.html')

    filesWindow.once('ready-to-show', () => {
      this.show()
    })
  })

  ipcMain.on('new-file', () => {
    const mainWindow = new BrowserWindow({
      width: 1200,
      height: 700,
      webPreferences: {
        nodeIntegration: true
      }
    })
  
    mainWindow.loadFile('./component/index/index.html')
  })

  ipcMain.on('save-file', (event, html, name) => {
    var fileName = 'files/' + name + '.txt'
    var txtPath = path.join(__dirname, fileName)
    var isSure = null
    fs.writeFile(txtPath, html, (err) => {
      if (err) {
        isSure = false
        event.sender.send('save-success', isSure)    
      } else {
        isSure = true
        event.sender.send('save-success', isSure)
      }
    })
  })

  ipcMain.on('open-file', (event, num) => {
    console.log(num)
    const mainWindow = new BrowserWindow({
      width: 1200,
      height: 700,
      webPreferences: {
        nodeIntegration: true
      }
    })
  
    mainWindow.loadFile('./component/index/index.html')
  })
})

// const menu = Menu.buildFromTemplate([])

// Menu.setApplicationMenu(menu)
